/**
 * 深度学习Fuzz测试模式
 * 重点分析：
 * 1. data参数的各种使用方式
 * 2. size参数的范围检查
 * 3. 数据转换模式 (data → 各种类型)
 * 4. BUILD.gn的完整配置
 */

const fs = require('fs');
const path = require('path');

class FuzzPatternDeepLearner {
    constructor() {
        this.patterns = {
            dataUsagePatterns: [],      // data参数使用模式
            sizeCheckPatterns: [],       // size检查模式
            dataConversionPatterns: [],  // data转换模式
            parameterExtractionPatterns: [], // 参数提取模式
            buildGnPatterns: [],         // BUILD.gn完整配置
            messageParcelPatterns: [],   // MessageParcel使用模式
            fuzzedDataProviderPatterns: [], // FuzzedDataProvider模式
            boundaryCheckPatterns: []    // 边界检查模式
        };
    }

    /**
     * 递归查找所有Fuzz文件
     */
    findAllFuzzFiles(dir, files = []) {
        const items = fs.readdirSync(dir, { withFileTypes: true });
        
        for (const item of items) {
            const fullPath = path.join(dir, item.name);
            
            if (item.isDirectory()) {
                // 跳过node_modules等
                if (!item.name.startsWith('.') && item.name !== 'node_modules') {
                    this.findAllFuzzFiles(fullPath, files);
                }
            } else if (item.name.endsWith('_fuzzer.cpp') || item.name.endsWith('_fuzz.cpp')) {
                files.push(fullPath);
            }
        }
        
        return files;
    }

    /**
     * 查找对应的BUILD.gn
     */
    findBuildGn(fuzzerCppPath) {
        const dir = path.dirname(fuzzerCppPath);
        const gnPath = path.join(dir, 'BUILD.gn');
        
        if (fs.existsSync(gnPath)) {
            return gnPath;
        }
        return null;
    }

    /**
     * 分析单个Fuzz文件
     */
    analyzeFuzzFile(filePath) {
        console.log(`\n📄 分析: ${path.basename(filePath)}`);
        
        const content = fs.readFileSync(filePath, 'utf-8');
        const lines = content.split('\n');
        
        const analysis = {
            filePath,
            fileName: path.basename(filePath),
            
            // 1. data使用方式
            dataUsages: this.extractDataUsages(content, lines),
            
            // 2. size检查方式
            sizeChecks: this.extractSizeChecks(content, lines),
            
            // 3. 数据转换方式
            conversions: this.extractConversions(content, lines),
            
            // 4. 参数提取方式
            parameterExtractions: this.extractParameterExtractions(content, lines),
            
            // 5. MessageParcel使用
            messageParcelUsage: this.extractMessageParcelUsage(content, lines),
            
            // 6. FuzzedDataProvider使用
            fuzzedDataProviderUsage: this.extractFuzzedDataProviderUsage(content, lines),
            
            // 7. 边界检查
            boundaryChecks: this.extractBoundaryChecks(content, lines),
            
            // 8. 函数签名
            fuzzFunctionSignature: this.extractFuzzFunctionSignature(content),
            
            // 9. includes
            includes: this.extractIncludes(content)
        };
        
        // 分析对应的BUILD.gn
        const gnPath = this.findBuildGn(filePath);
        if (gnPath) {
            analysis.buildGn = this.analyzeBuildGn(gnPath);
        }
        
        return analysis;
    }

    /**
     * 提取data使用模式
     */
    extractDataUsages(content, lines) {
        const usages = [];
        const patterns = [
            // 直接使用data
            { pattern: /const\s+uint8_t\s*\*\s*(\w+)\s*=\s*data/, type: 'direct_pointer' },
            { pattern: /uint8_t\s*\*\s*(\w+)\s*=\s*\(uint8_t\s*\*\)\s*data/, type: 'cast_pointer' },
            
            // 从data读取
            { pattern: /data\[([\w\s+\-*\/]+)\]/, type: 'array_access' },
            { pattern: /\*\((\w+)\s*\*\)\s*data/, type: 'pointer_cast_deref' },
            { pattern: /\*\((\w+)\s*\*\)\s*\(data\s*\+\s*(\w+)\)/, type: 'offset_cast_deref' },
            
            // memcpy
            { pattern: /memcpy\s*\([^,]+,\s*data/, type: 'memcpy_from_data' },
            { pattern: /memcpy_s\s*\([^,]+,\s*[^,]+,\s*data/, type: 'memcpy_s_from_data' },
            
            // std::string
            { pattern: /std::string\s*\(\s*reinterpret_cast<const\s+char\s*\*>\s*\(data\)/, type: 'string_from_data' },
            { pattern: /std::string\s*\(\(const\s+char\s*\*\)data/, type: 'string_from_data_cast' },
            
            // MessageParcel
            { pattern: /WriteBuffer\s*\(\s*data,\s*size\)/, type: 'parcel_write_buffer' },
            { pattern: /WriteRawData\s*\(\s*data,\s*size\)/, type: 'parcel_write_raw' },
            
            // FuzzedDataProvider
            { pattern: /FuzzedDataProvider\s+\w+\s*\(\s*data,\s*size\)/, type: 'fuzzed_data_provider' }
        ];
        
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            
            for (const p of patterns) {
                const match = line.match(p.pattern);
                if (match) {
                    usages.push({
                        type: p.type,
                        line: i + 1,
                        code: line,
                        match: match[0]
                    });
                }
            }
        }
        
        return usages;
    }

    /**
     * 提取size检查模式
     */
    extractSizeChecks(content, lines) {
        const checks = [];
        const patterns = [
            // 最小size检查
            { pattern: /if\s*\(\s*size\s*<\s*(\d+)/, type: 'min_size_check', extract: 'minSize' },
            { pattern: /if\s*\(\s*size\s*<\s*sizeof\s*\(([^)]+)\)/, type: 'sizeof_check', extract: 'type' },
            { pattern: /if\s*\(\s*size\s*<=\s*(\d+)/, type: 'min_size_check_le', extract: 'minSize' },
            
            // 最大size检查
            { pattern: /if\s*\(\s*size\s*>\s*(\d+)/, type: 'max_size_check', extract: 'maxSize' },
            { pattern: /if\s*\(\s*size\s*>=\s*(\d+)/, type: 'max_size_check_ge', extract: 'maxSize' },
            
            // 范围检查
            { pattern: /if\s*\(\s*size\s*<\s*(\d+)\s*\|\|\s*size\s*>\s*(\d+)/, type: 'range_check', extract: 'range' },
            
            // 空检查
            { pattern: /if\s*\(\s*data\s*==\s*nullptr\s*\|\|\s*size\s*==\s*0/, type: 'null_empty_check' },
            { pattern: /if\s*\(\s*data\s*==\s*nullptr\s*\|\|\s*size\s*</, type: 'null_size_check' },
            
            // 返回条件
            { pattern: /return\s*;.*size\s*</, type: 'early_return' }
        ];
        
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            
            for (const p of patterns) {
                const match = line.match(p.pattern);
                if (match) {
                    checks.push({
                        type: p.type,
                        line: i + 1,
                        code: line,
                        value: match[1] || null,
                        value2: match[2] || null
                    });
                }
            }
        }
        
        return checks;
    }

    /**
     * 提取数据转换模式
     */
    extractConversions(content, lines) {
        const conversions = [];
        const patterns = [
            // 基本类型转换
            { pattern: /\*\s*reinterpret_cast<const\s+(\w+)\s*\*>\s*\(data/, type: 'reinterpret_cast', targetType: '$1' },
            { pattern: /\(\s*(\w+)\s*\*\s*\)\s*data/, type: 'c_style_cast', targetType: '$1' },
            { pattern: /static_cast<(\w+)>\s*\(\*data\)/, type: 'static_cast', targetType: '$1' },
            
            // 字符串转换
            { pattern: /std::string\s+(\w+)\s*\(\s*reinterpret_cast<const\s+char\s*\*>\s*\(data\),\s*size/, type: 'string_with_size' },
            { pattern: /std::string\s+(\w+)\s*\(\(const\s+char\s*\*\)data\)/, type: 'string_simple' },
            { pattern: /std::string\s+(\w+)\s*=\s*std::string\s*\(data,\s*data\s*\+\s*size\)/, type: 'string_iterator' },
            
            // 数值提取
            { pattern: /uint(\d+)_t\s+(\w+)\s*=\s*\*\(uint\d+_t\s*\*\)\s*data/, type: 'uint_from_data' },
            { pattern: /int(\d+)_t\s+(\w+)\s*=\s*\*\(int\d+_t\s*\*\)\s*data/, type: 'int_from_data' },
            { pattern: /bool\s+(\w+)\s*=\s*\*data/, type: 'bool_from_data' },
            
            // 偏移读取
            { pattern: /data\s*\+\s*(\d+)/, type: 'offset_read', offset: '$1' },
            { pattern: /data\s*\+\s*sizeof\s*\(([^)]+)\)/, type: 'sizeof_offset', offsetType: '$1' }
        ];
        
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            
            for (const p of patterns) {
                const match = line.match(p.pattern);
                if (match) {
                    conversions.push({
                        type: p.type,
                        line: i + 1,
                        code: line,
                        details: match
                    });
                }
            }
        }
        
        return conversions;
    }

    /**
     * 提取参数提取模式
     */
    extractParameterExtractions(content, lines) {
        const extractions = [];
        
        // 查找FuzzedDataProvider模式
        const fdpMatch = content.match(/FuzzedDataProvider\s+(\w+)\s*\(\s*data,\s*size\)/);
        if (fdpMatch) {
            const fdpName = fdpMatch[1];
            
            // 查找所有使用这个provider的地方
            const usagePatterns = [
                { pattern: new RegExp(`${fdpName}\\.ConsumeBool\\(\\)`), type: 'ConsumeBool' },
                { pattern: new RegExp(`${fdpName}\\.ConsumeIntegral<(\\w+)>\\(\\)`), type: 'ConsumeIntegral' },
                { pattern: new RegExp(`${fdpName}\\.ConsumeIntegralInRange<(\\w+)>\\((\\d+),\\s*(\\d+)\\)`), type: 'ConsumeIntegralInRange' },
                { pattern: new RegExp(`${fdpName}\\.ConsumeFloatingPoint<(\\w+)>\\(\\)`), type: 'ConsumeFloatingPoint' },
                { pattern: new RegExp(`${fdpName}\\.ConsumeRandomLengthString\\((\\d+)\\)`), type: 'ConsumeRandomLengthString' },
                { pattern: new RegExp(`${fdpName}\\.ConsumeRemainingBytes\\(\\)`), type: 'ConsumeRemainingBytes' },
                { pattern: new RegExp(`${fdpName}\\.ConsumeBytes<uint8_t>\\((\\d+)\\)`), type: 'ConsumeBytes' }
            ];
            
            for (let i = 0; i < lines.length; i++) {
                const line = lines[i];
                for (const p of usagePatterns) {
                    const match = line.match(p.pattern);
                    if (match) {
                        extractions.push({
                            method: p.type,
                            line: i + 1,
                            code: line.trim(),
                            details: match
                        });
                    }
                }
            }
        }
        
        return extractions;
    }

    /**
     * 提取MessageParcel使用模式
     */
    extractMessageParcelUsage(content, lines) {
        const usages = [];
        
        if (content.includes('MessageParcel')) {
            // 查找WriteBuffer/WriteRawData
            for (let i = 0; i < lines.length; i++) {
                const line = lines[i];
                
                if (line.includes('WriteBuffer') || line.includes('WriteRawData')) {
                    usages.push({
                        type: 'write',
                        line: i + 1,
                        code: line.trim()
                    });
                }
                
                if (line.includes('ReadBuffer') || line.includes('ReadRawData')) {
                    usages.push({
                        type: 'read',
                        line: i + 1,
                        code: line.trim()
                    });
                }
            }
        }
        
        return usages;
    }

    /**
     * 提取FuzzedDataProvider使用模式
     */
    extractFuzzedDataProviderUsage(content, lines) {
        if (!content.includes('FuzzedDataProvider')) {
            return null;
        }
        
        const usage = {
            hasProvider: true,
            methods: []
        };
        
        // 提取所有Consume方法
        const consumeMethods = content.match(/\.\s*Consume\w+\([^)]*\)/g) || [];
        usage.methods = consumeMethods.map(m => m.trim());
        
        return usage;
    }

    /**
     * 提取边界检查模式
     */
    extractBoundaryChecks(content, lines) {
        const checks = [];
        
        const patterns = [
            /if\s*\(\s*size\s*<\s*\d+\s*\)/,
            /if\s*\(\s*size\s*==\s*0\s*\)/,
            /if\s*\(\s*data\s*==\s*nullptr\s*\)/,
            /if\s*\(\s*\w+\s*>=\s*size\s*\)/,
            /if\s*\(\s*\w+\s*\+\s*\w+\s*>\s*size\s*\)/
        ];
        
        for (let i = 0; i < lines.length; i++) {
            const line = lines[i].trim();
            for (const pattern of patterns) {
                if (pattern.test(line)) {
                    checks.push({
                        line: i + 1,
                        code: line
                    });
                }
            }
        }
        
        return checks;
    }

    /**
     * 提取Fuzz函数签名
     */
    extractFuzzFunctionSignature(content) {
        const match = content.match(/extern\s+"C"\s+int\s+LLVMFuzzerTestOneInput\s*\(\s*const\s+uint8_t\s*\*\s*data,\s*size_t\s+size\s*\)/);
        return match ? match[0] : null;
    }

    /**
     * 提取includes
     */
    extractIncludes(content) {
        const includes = [];
        const lines = content.split('\n');
        
        for (const line of lines) {
            const match = line.match(/#include\s+[<"]([^>"]+)[>"]/);
            if (match) {
                includes.push(match[1]);
            }
        }
        
        return includes;
    }

    /**
     * 分析BUILD.gn
     */
    analyzeBuildGn(gnPath) {
        console.log(`  📦 BUILD.gn: ${path.basename(path.dirname(gnPath))}`);
        
        const content = fs.readFileSync(gnPath, 'utf-8');
        
        return {
            filePath: gnPath,
            moduleOutPath: this.extractField(content, 'module_out_path'),
            sources: this.extractArrayField(content, 'sources'),
            includeDirs: this.extractArrayField(content, 'include_dirs'),
            cflags: this.extractArrayField(content, 'cflags'),
            deps: this.extractArrayField(content, 'deps'),
            externalDeps: this.extractArrayField(content, 'external_deps'),
            defines: this.extractArrayField(content, 'defines'),
            fullContent: content
        };
    }

    extractField(content, fieldName) {
        const match = content.match(new RegExp(`${fieldName}\\s*=\\s*"([^"]+)"`));
        return match ? match[1] : null;
    }

    extractArrayField(content, fieldName) {
        const match = content.match(new RegExp(`${fieldName}\\s*=\\s*\\[([^\\]]+)\\]`, 's'));
        if (!match) return [];
        
        const items = match[1].match(/"([^"]+)"/g) || [];
        return items.map(item => item.replace(/"/g, ''));
    }

    /**
     * 统计分析
     */
    generateStatistics(analyses) {
        console.log('\n\n' + '='.repeat(80));
        console.log('📊 Fuzz模式深度分析统计报告');
        console.log('='.repeat(80));
        
        // 1. 总体统计
        console.log('\n【1️⃣  总体统计】');
        console.log(`  分析文件数: ${analyses.length}个`);
        console.log(`  有BUILD.gn: ${analyses.filter(a => a.buildGn).length}个`);
        
        // 2. size检查模式统计
        console.log('\n【2️⃣  size检查模式】');
        const sizeCheckTypes = {};
        const sizeCheckValues = [];
        
        analyses.forEach(a => {
            a.sizeChecks.forEach(check => {
                sizeCheckTypes[check.type] = (sizeCheckTypes[check.type] || 0) + 1;
                if (check.value) {
                    sizeCheckValues.push(parseInt(check.value));
                }
            });
        });
        
        console.log('  检查类型分布:');
        Object.entries(sizeCheckTypes).sort((a, b) => b[1] - a[1]).forEach(([type, count]) => {
            console.log(`    ✓ ${type.padEnd(25)} - ${count}次`);
        });
        
        if (sizeCheckValues.length > 0) {
            const minSizes = sizeCheckValues.filter(v => v < 1000);
            const freqMap = {};
            minSizes.forEach(v => freqMap[v] = (freqMap[v] || 0) + 1);
            console.log('\n  常见最小size值:');
            Object.entries(freqMap).sort((a, b) => b[1] - a[1]).slice(0, 10).forEach(([size, count]) => {
                console.log(`    ✓ ${size}字节 - 出现${count}次`);
            });
        }
        
        // 3. data使用模式统计
        console.log('\n【3️⃣  data使用模式】');
        const dataUsageTypes = {};
        
        analyses.forEach(a => {
            a.dataUsages.forEach(usage => {
                dataUsageTypes[usage.type] = (dataUsageTypes[usage.type] || 0) + 1;
            });
        });
        
        console.log('  使用方式分布:');
        Object.entries(dataUsageTypes).sort((a, b) => b[1] - a[1]).forEach(([type, count]) => {
            console.log(`    ✓ ${type.padEnd(30)} - ${count}次`);
        });
        
        // 4. 数据转换模式统计
        console.log('\n【4️⃣  数据转换模式】');
        const conversionTypes = {};
        
        analyses.forEach(a => {
            a.conversions.forEach(conv => {
                conversionTypes[conv.type] = (conversionTypes[conv.type] || 0) + 1;
            });
        });
        
        console.log('  转换方式分布:');
        Object.entries(conversionTypes).sort((a, b) => b[1] - a[1]).forEach(([type, count]) => {
            console.log(`    ✓ ${type.padEnd(30)} - ${count}次`);
        });
        
        // 5. FuzzedDataProvider使用
        console.log('\n【5️⃣  FuzzedDataProvider使用】');
        const fdpCount = analyses.filter(a => a.fuzzedDataProviderUsage && a.fuzzedDataProviderUsage.hasProvider).length;
        console.log(`  使用FuzzedDataProvider: ${fdpCount}/${analyses.length} (${(fdpCount/analyses.length*100).toFixed(1)}%)`);
        
        if (fdpCount > 0) {
            const allMethods = [];
            analyses.forEach(a => {
                if (a.fuzzedDataProviderUsage) {
                    allMethods.push(...a.fuzzedDataProviderUsage.methods);
                }
            });
            const methodFreq = {};
            allMethods.forEach(m => {
                const methodName = m.match(/\.\s*(\w+)\(/)?.[1];
                if (methodName) {
                    methodFreq[methodName] = (methodFreq[methodName] || 0) + 1;
                }
            });
            console.log('  常用方法:');
            Object.entries(methodFreq).sort((a, b) => b[1] - a[1]).slice(0, 10).forEach(([method, count]) => {
                console.log(`    ✓ ${method.padEnd(30)} - ${count}次`);
            });
        }
        
        // 6. MessageParcel使用
        console.log('\n【6️⃣  MessageParcel使用】');
        const parcelCount = analyses.filter(a => a.messageParcelUsage.length > 0).length;
        console.log(`  使用MessageParcel: ${parcelCount}/${analyses.length} (${(parcelCount/analyses.length*100).toFixed(1)}%)`);
        
        // 7. BUILD.gn配置统计
        console.log('\n【7️⃣  BUILD.gn配置统计】');
        const gnAnalyses = analyses.filter(a => a.buildGn);
        
        if (gnAnalyses.length > 0) {
            const allExternalDeps = {};
            const allIncludes = {};
            
            gnAnalyses.forEach(a => {
                a.buildGn.externalDeps.forEach(dep => {
                    allExternalDeps[dep] = (allExternalDeps[dep] || 0) + 1;
                });
                a.buildGn.includeDirs.forEach(inc => {
                    allIncludes[inc] = (allIncludes[inc] || 0) + 1;
                });
            });
            
            console.log('  高频external_deps (Top 15):');
            Object.entries(allExternalDeps).sort((a, b) => b[1] - a[1]).slice(0, 15).forEach(([dep, count]) => {
                const ratio = (count / gnAnalyses.length * 100).toFixed(0);
                console.log(`    ✓ ${dep.padEnd(35)} - ${count}次 (${ratio}%)`);
            });
            
            console.log('\n  高频include_dirs模式 (Top 10):');
            Object.entries(allIncludes).sort((a, b) => b[1] - a[1]).slice(0, 10).forEach(([inc, count]) => {
                console.log(`    ✓ ${inc}`);
            });
        }
    }

    /**
     * 生成最佳实践示例
     */
    generateBestPractices(analyses) {
        console.log('\n\n' + '='.repeat(80));
        console.log('✨ Fuzz测试最佳实践总结');
        console.log('='.repeat(80));
        
        // 找几个典型示例
        const withFDP = analyses.find(a => a.fuzzedDataProviderUsage && a.fuzzedDataProviderUsage.hasProvider);
        const withParcel = analyses.find(a => a.messageParcelUsage.length > 0);
        const withSizeCheck = analyses.find(a => a.sizeChecks.length > 0);
        
        if (withSizeCheck) {
            console.log('\n【示例1: 标准size检查】');
            console.log(`文件: ${withSizeCheck.fileName}`);
            withSizeCheck.sizeChecks.slice(0, 3).forEach(check => {
                console.log(`  ${check.code}`);
            });
        }
        
        if (withFDP) {
            console.log('\n【示例2: FuzzedDataProvider使用】');
            console.log(`文件: ${withFDP.fileName}`);
            if (withFDP.parameterExtractions.length > 0) {
                withFDP.parameterExtractions.slice(0, 5).forEach(ext => {
                    console.log(`  ${ext.code}`);
                });
            }
        }
        
        if (withParcel) {
            console.log('\n【示例3: MessageParcel使用】');
            console.log(`文件: ${withParcel.fileName}`);
            withParcel.messageParcelUsage.slice(0, 3).forEach(usage => {
                console.log(`  ${usage.code}`);
            });
        }
    }

    /**
     * 保存详细分析结果
     */
    saveDetailedAnalysis(analyses) {
        const outputPath = 'core/knowledge/fuzz-deep-analysis.json';
        
        const summary = {
            timestamp: new Date().toISOString(),
            totalFiles: analyses.length,
            
            // 提取核心模式
            corePatterns: {
                sizeCheckPatterns: this.extractSizeCheckPatterns(analyses),
                dataUsagePatterns: this.extractDataUsagePatterns(analyses),
                conversionPatterns: this.extractConversionPatterns(analyses),
                buildGnPatterns: this.extractBuildGnPatterns(analyses),
                fuzzedDataProviderPatterns: this.extractFDPPatterns(analyses),
                messageParcelPatterns: this.extractMessageParcelPatterns(analyses)
            },
            
            // 完整示例
            bestExamples: this.selectBestExamples(analyses, 30),
            
            // 详细分析（可选，数据量大）
            // detailedAnalyses: analyses
        };
        
        fs.writeFileSync(outputPath, JSON.stringify(summary, null, 2));
        console.log(`\n✅ 详细分析已保存到: ${outputPath}`);
        console.log(`   文件大小: ${(fs.statSync(outputPath).size / 1024).toFixed(2)} KB`);
    }

    extractSizeCheckPatterns(analyses) {
        const patterns = [];
        const freqMap = {};
        
        analyses.forEach(a => {
            a.sizeChecks.forEach(check => {
                const key = `${check.type}_${check.value || 'dynamic'}`;
                if (!freqMap[key]) {
                    freqMap[key] = { ...check, count: 0 };
                }
                freqMap[key].count++;
            });
        });
        
        return Object.values(freqMap).sort((a, b) => b.count - a.count).slice(0, 20);
    }

    extractDataUsagePatterns(analyses) {
        const patterns = [];
        const freqMap = {};
        
        analyses.forEach(a => {
            a.dataUsages.forEach(usage => {
                if (!freqMap[usage.type]) {
                    freqMap[usage.type] = { type: usage.type, examples: [], count: 0 };
                }
                freqMap[usage.type].count++;
                if (freqMap[usage.type].examples.length < 3) {
                    freqMap[usage.type].examples.push(usage.code);
                }
            });
        });
        
        return Object.values(freqMap).sort((a, b) => b.count - a.count);
    }

    extractConversionPatterns(analyses) {
        const patterns = [];
        const freqMap = {};
        
        analyses.forEach(a => {
            a.conversions.forEach(conv => {
                if (!freqMap[conv.type]) {
                    freqMap[conv.type] = { type: conv.type, examples: [], count: 0 };
                }
                freqMap[conv.type].count++;
                if (freqMap[conv.type].examples.length < 3) {
                    freqMap[conv.type].examples.push(conv.code);
                }
            });
        });
        
        return Object.values(freqMap).sort((a, b) => b.count - a.count);
    }

    extractBuildGnPatterns(analyses) {
        const gnAnalyses = analyses.filter(a => a.buildGn);
        if (gnAnalyses.length === 0) return {};
        
        const allExternalDeps = {};
        const allIncludes = {};
        const allCflags = {};
        
        gnAnalyses.forEach(a => {
            a.buildGn.externalDeps.forEach(dep => {
                allExternalDeps[dep] = (allExternalDeps[dep] || 0) + 1;
            });
            a.buildGn.includeDirs.forEach(inc => {
                allIncludes[inc] = (allIncludes[inc] || 0) + 1;
            });
            a.buildGn.cflags.forEach(flag => {
                allCflags[flag] = (allCflags[flag] || 0) + 1;
            });
        });
        
        return {
            highFreqExternalDeps: Object.entries(allExternalDeps)
                .sort((a, b) => b[1] - a[1])
                .slice(0, 30)
                .map(([dep, count]) => ({ dep, count, frequency: count / gnAnalyses.length })),
            
            commonIncludes: Object.entries(allIncludes)
                .sort((a, b) => b[1] - a[1])
                .slice(0, 20)
                .map(([inc, count]) => ({ include: inc, count })),
            
            commonCflags: Object.entries(allCflags)
                .sort((a, b) => b[1] - a[1])
                .map(([flag, count]) => ({ flag, count }))
        };
    }

    extractFDPPatterns(analyses) {
        const withFDP = analyses.filter(a => a.fuzzedDataProviderUsage && a.fuzzedDataProviderUsage.hasProvider);
        
        if (withFDP.length === 0) return null;
        
        const allExtractions = [];
        withFDP.forEach(a => {
            allExtractions.push(...a.parameterExtractions);
        });
        
        const methodFreq = {};
        allExtractions.forEach(ext => {
            methodFreq[ext.method] = (methodFreq[ext.method] || 0) + 1;
        });
        
        return {
            usageRate: withFDP.length / analyses.length,
            commonMethods: Object.entries(methodFreq)
                .sort((a, b) => b[1] - a[1])
                .map(([method, count]) => ({ method, count })),
            examples: withFDP.slice(0, 5).map(a => ({
                file: a.fileName,
                extractions: a.parameterExtractions.slice(0, 5)
            }))
        };
    }

    extractMessageParcelPatterns(analyses) {
        const withParcel = analyses.filter(a => a.messageParcelUsage.length > 0);
        
        if (withParcel.length === 0) return null;
        
        return {
            usageRate: withParcel.length / analyses.length,
            examples: withParcel.slice(0, 10).map(a => ({
                file: a.fileName,
                usages: a.messageParcelUsage
            }))
        };
    }

    selectBestExamples(analyses, count = 30) {
        // 选择最有代表性的示例
        const scored = analyses.map(a => {
            let score = 0;
            
            // 有size检查
            if (a.sizeChecks.length > 0) score += 10;
            
            // 有数据转换
            score += Math.min(a.conversions.length * 2, 20);
            
            // 使用FuzzedDataProvider
            if (a.fuzzedDataProviderUsage && a.fuzzedDataProviderUsage.hasProvider) score += 15;
            
            // 使用MessageParcel
            if (a.messageParcelUsage.length > 0) score += 15;
            
            // 有BUILD.gn
            if (a.buildGn) score += 10;
            
            // 有参数提取
            score += Math.min(a.parameterExtractions.length * 3, 20);
            
            return { analysis: a, score };
        });
        
        return scored
            .sort((a, b) => b.score - a.score)
            .slice(0, count)
            .map(s => s.analysis);
    }

    /**
     * 主执行函数
     */
    async run() {
        console.log('🚀 开始深度学习Fuzz测试模式...\n');
        
        const ohcodePath = 'OHCode';
        if (!fs.existsSync(ohcodePath)) {
            console.error('❌ OHCode目录不存在!');
            return;
        }
        
        // 1. 查找所有Fuzz文件
        console.log('📂 正在扫描Fuzz文件...');
        const fuzzFiles = this.findAllFuzzFiles(ohcodePath);
        console.log(`✓ 找到 ${fuzzFiles.length} 个Fuzz测试文件\n`);
        
        // 2. 分析每个文件
        console.log('🔍 开始深度分析...');
        const analyses = [];
        let analyzed = 0;
        
        for (const file of fuzzFiles) {
            try {
                const analysis = this.analyzeFuzzFile(file);
                analyses.push(analysis);
                analyzed++;
                
                if (analyzed % 50 === 0) {
                    console.log(`  已分析 ${analyzed}/${fuzzFiles.length}...`);
                }
            } catch (error) {
                console.error(`  ⚠️  分析失败: ${path.basename(file)} - ${error.message}`);
            }
        }
        
        console.log(`\n✓ 完成分析 ${analyses.length} 个文件\n`);
        
        // 3. 生成统计报告
        this.generateStatistics(analyses);
        
        // 4. 生成最佳实践
        this.generateBestPractices(analyses);
        
        // 5. 保存详细分析
        this.saveDetailedAnalysis(analyses);
        
        console.log('\n' + '='.repeat(80));
        console.log('✅ 深度学习完成！');
        console.log('='.repeat(80));
    }
}

// 执行
const learner = new FuzzPatternDeepLearner();
learner.run().catch(error => {
    console.error('❌ 执行失败:', error);
});

